package org.lgiavedoni.android.franq.command.system;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.lgiavedoni.android.franq.core.command.Command;
import org.lgiavedoni.android.franq.core.service.Service;
import org.lgiavedoni.android.franq.core.service.ServiceManager;
import org.lgiavedoni.android.franq.core.speak.CommonPhraseHelper;

public class ServiceCommand extends Command {

	private static final String OPTION_START = "start";
	private static final String OPTION_STOP = "stop";
	private static final String OPTION_RESTART = "restart";
	private static final String OPTION_INFO = "info";
	private static final String OPTION_ENABLE = "enable";
	private static final String OPTION_DISABLE = "disable";

	@Override
	public void setOptions(Options options) {
		options.addOption(OPTION_START, false, "Start sevice");
		options.addOption(OPTION_STOP, false, "Stop sevice");
		options.addOption(OPTION_RESTART, false, "Restart sevice");
		options.addOption(OPTION_INFO, false, "Get service info");
		options.addOption(OPTION_ENABLE, false, "Enable service");
		options.addOption(OPTION_DISABLE, false, "Disable service");
	}

	@Override
	public boolean execute(CommandLine cmd) throws Exception {

		if (cmd.getArgList() != null && cmd.getArgList().size() == 1) {

			// Get the specific service
			Service service = ServiceManager.inst.getService(cmd.getArgList().get(0).toString());
			if (service == null) {
				sendText("Service [" + cmd.getArgList().get(0).toString() + "] not found");
				return false;
			}

			if (cmd.hasOption(OPTION_INFO)) {
				sendText(service.getFullInfo());
				return true;
			}

			if (cmd.hasOption(OPTION_RESTART))
				service.restart();
			if (cmd.hasOption(OPTION_START))
				service.start();
			if (cmd.hasOption(OPTION_STOP))
				service.stop();

			if (cmd.hasOption(OPTION_ENABLE))
				service.setEnable(true);

			if (cmd.hasOption(OPTION_DISABLE))
				service.setEnable(false);

			if (cmd.hasOption(OPTION_RESTART) || cmd.hasOption(OPTION_START) || cmd.hasOption(OPTION_STOP) || cmd.hasOption(OPTION_ENABLE) || cmd.hasOption(OPTION_DISABLE)) {
				sendText(CommonPhraseHelper.DONE.getValue());
				return true;
			}

		} else {
			StringBuffer status = new StringBuffer();
			// Show all services
			for (Service s : ServiceManager.inst.getAllServices()) {
				status.append(s.getServiceName() + " --> " + s.getStatus() + "\n");
			}
			sendText(status.toString());
			return true;
		}
		return false;
	}

	@Override
	public String getCommandText() {
		return "service";
	}

}
